/*
 * @Author: Zhengxuan Ye
 * @Date: 2025-05-06 21:28:44
 * @Last Modified by:   Zhengxuan Ye
 * @Last Modified time: 2025-05-06 21:28:44
 */

import { defineStore } from 'pinia'
import axios from 'axios'

// API基础URL
const API_URL = 'http://localhost:3000/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    user: null,
    loading: false,
    error: null,
  }),

  getters: {
    isLoggedIn: (state) => {
      const loggedIn = !!state.token && !!state.user
      console.log(
        '用户登录状态检查 - Token:',
        !!state.token,
        'User:',
        !!state.user,
        'Result:',
        loggedIn,
      )
      return loggedIn
    },
    isAdmin: (state) => {
      return state.user?.isAdmin === true
    },
  },

  actions: {
    // 检查认证状态
    async checkAuth() {
      console.log('检查认证状态，当前token:', this.token ? '存在' : '不存在')

      if (!this.token) {
        console.log('没有token，跳过认证检查')
        return false
      }

      try {
        this.loading = true
        console.log('发送认证检查请求，URL:', `${API_URL}/user/me`)
        console.log('请求头:', { Authorization: `Bearer ${this.token}` })

        const response = await axios.get(`${API_URL}/user/me`, {
          headers: { Authorization: `Bearer ${this.token}` },
          // 添加withCredentials以确保跨域请求包含凭证
          withCredentials: true,
        })

        console.log('认证检查响应:', response.data)

        if (response.data && response.data.user) {
          this.user = response.data.user
          console.log('用户信息已更新:', this.user)
          this.loading = false
          return true
        } else {
          console.error('认证响应中没有用户信息')
          this.logout()
          this.loading = false
          return false
        }
      } catch (error) {
        console.error('认证检查失败:', error.message)
        console.error('错误详情:', error.response?.data || '无响应数据')
        console.log('认证失败，执行登出操作')
        this.logout()
        this.loading = false
        return false
      }
    },

    // 用户注册
    async register(userData) {
      try {
        this.loading = true
        this.error = null

        const response = await axios.post(`${API_URL}/user/register`, userData)

        this.token = response.data.token
        this.user = response.data.user

        // 保存token到本地存储
        localStorage.setItem('token', this.token)

        this.loading = false
        return true
      } catch (error) {
        console.error('注册失败:', error)
        this.error = error.response?.data?.message || '注册失败，请稍后再试'
        this.loading = false
        return false
      }
    },

    // 用户登录
    async login(credentials) {
      try {
        this.loading = true
        this.error = null

        // 确保包含验证码信息
        if (!credentials.captchaId || !credentials.captcha) {
          this.error = '请输入验证码'
          this.loading = false
          return false
        }

        console.log('发送登录请求，URL:', `${API_URL}/user/login`, '数据:', credentials)
        const response = await axios.post(`${API_URL}/user/login`, credentials, {
          withCredentials: true,
        })
        console.log('登录响应:', response.data)

        this.token = response.data.token
        this.user = response.data.user

        // 保存token到本地存储
        localStorage.setItem('token', this.token)

        // 打印登录状态
        console.log('登录成功，token:', this.token)
        console.log('登录成功，用户信息:', this.user)
        console.log('登录状态:', this.isLoggedIn)

        this.loading = false
        return true
      } catch (error) {
        console.error('登录失败:', error)
        if (error.response?.data?.message.includes('验证码')) {
          this.error = error.response.data.message
        } else {
          this.error = error.response?.data?.message || '登录失败，请检查用户名和密码'
        }
        this.loading = false
        return false
      }
    },

    // 用户登出
    logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
    },

    // 设置用户信息
    setUser(user) {
      this.user = user
    },

    // 设置Token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },
  },
})
